package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.dubbo.api.AudioApi;
import com.tanhua.dubbo.enums.IdType;
import com.tanhua.dubbo.pojo.Audio;
import com.tanhua.dubbo.service.IdService;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@DubboService(version = "1.0.0")
public class AudioApiImpl implements AudioApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //用户今日获取语音剩余的次数前缀
    private static final String TAOHUA_AUDIO_LAST_COUNT = "TAOHUA_AUDIO_LAST_COUNT_";

    //存储桃花传音匹配到过的用户id的大key
    private static final String TAOHUA_AUDIO_RECOMMEND = "TAOHUA_AUDIO_RECOMMEND_";

    //存储桃花传音匹配到过的用户id的hash key的前缀
    private static final String HASH_KEY = "USER__";


    /**
     * 保存语音
     *
     * @param audio
     * @return 保存成功后，返回语音id
     */
    @Override
    public String saveAudio(Audio audio) {
        //校验
        if (!ObjectUtil.isAllNotEmpty(audio.getUserId(), audio.getSoundUrl())) {
            return null;
        }

        audio.setId(ObjectId.get());
        audio.setAid(this.idService.createId(IdType.AUDIO)); //自增长的id
        audio.setCreated(System.currentTimeMillis());

        this.mongoTemplate.save(audio);
        return audio.getId().toString();
    }

    /**
     * 根据id查询语音
     *
     * @param audioId
     * @return
     */
    @Override
    public Audio queryAudioById(String audioId) {
        return this.mongoTemplate.findById(new ObjectId(audioId), Audio.class);
    }

    /**
     * 查询用户今日获取语音剩余的次数
     *
     * @param userId
     * @return
     */
    @Override
    public Integer queryCount(Long userId) {
        String redisKey = this.TAOHUA_AUDIO_LAST_COUNT + userId;
        if (!this.redisTemplate.hasKey(redisKey)) {
            //今日剩余毫秒
            long todayLastTime = DateUtil.endOfDay(new Date()).getTime() - System.currentTimeMillis();
            this.redisTemplate.opsForValue().set(redisKey, "0", todayLastTime, TimeUnit.SECONDS);
        }
        return (10 - Convert.toInt(this.redisTemplate.opsForValue().get(redisKey)));

    }


    /**
     * 随机获取一条语音
     *
     * @param userId
     * @return
     */
    @Override
    public Audio getSound(Long userId) {
        String redisKey = this.TAOHUA_AUDIO_RECOMMEND;
        String hashKey = this.HASH_KEY + userId;

        //获取已经收到过的语音的aid
        String strAidList = Convert.toStr(this.redisTemplate.opsForHash().get(redisKey, hashKey), "");

        List<Long> aidList = Convert.toList(Long.class, StrUtil.split(strAidList, ','));
        //获取所有的语音,排除自己发的语音和已经收到过的语音aid
        Query query = new Query(Criteria.where("userId").ne(userId).and("aid").nin(aidList));
        List<Audio> audioList = this.mongoTemplate.find(query, Audio.class);

        if (CollUtil.isEmpty(audioList)) {
            return null;
        }
        //打乱集合顺序,获取一条语音
        Collections.shuffle(audioList);
        Audio audio = audioList.get(0);
        //把这条语音的aid拼接到redis中对应的key中
        aidList.add(audio.getAid());
        strAidList = strAidList.length() == 0 ? audio.getAid().toString() : strAidList + "," + audio.getAid();
        this.redisTemplate.opsForHash().put(redisKey, hashKey, strAidList);
        //该用户的当天获取语音的次数加一
        this.redisTemplate.opsForValue().increment(this.TAOHUA_AUDIO_LAST_COUNT + userId);
        return audio;

    }


}
